/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Controllers;

import Model.Adresa;
import Model.Urole;
import Model.Uzivatel;
import ModelJava.SHA1hash;
import ModelJava.UserManager;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Lurtz
 */
@WebServlet(name="ControllerRegistrace", urlPatterns={"/ControllerRegistrace"})
public class ControllerRegistrace extends HttpServlet {

    String ejmeno = "Jmeno je spatne vyplneno";
    String eprij = "Prijmeni je spatne vyplneno";
    String etel = "Telefon musi mit 9 cifer";
    String eheslo = "Hesla se nerovnaji nebo je kratsi nez 6 znaku";
    String oheslo = "Heslo v poradku";
    String emesto = "Mesto spatne vyplneno";
    String eemail = "Email spatne vyplnen";
    String eulice = "Ulice spatne vyplnena";
    String epsc = "Psc musi mit 5 cifer";
    String ecp = "CP musi byt kladne cislo";

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String viewUrl = "/index.jsp";
        request.setAttribute("showPage", "registrace");

        try {
            HttpSession session = request.getSession();
            if (session == null) {
                viewUrl = "/error.jsp";
                System.out.println("Nastala chyba.");
            } else {
                if (session.isNew()) {
                    System.out.println("Nova Session.");

                }
                smazErr(session);
                //pokud bylo stisknuto tlacitko Odeslat, tak musim validovat formular
                if(request.getParameter("submit") != null && request.getParameter("submit").equals("Registrovat")){
                    //vytvoreni noveho uzivatele
                    if(session.getAttribute("novyUzivatel") == null){
                        session.setAttribute("novyUzivatel", new Uzivatel());
                    }
                    Uzivatel u =  (Uzivatel)session.getAttribute("novyUzivatel");
                    if(u.getAdresa() == null){
                        u.setAdresa(new Adresa());
                    }
                    System.err.println("jmeno: " + request.getParameter("jmeno"));
                    //pridavani validnich informaci do uzivatele
                    if(validateSlovo(request.getParameter("jmeno"))){
                        u.setJmeno(request.getParameter("jmeno"));
                    }else session.setAttribute("ejmeno", ejmeno);
                    System.err.println("prijmeni: " + request.getParameter("prijmeni"));
                    if(validateSlovo(request.getParameter("prijmeni"))){
                        u.setPrijmeni(request.getParameter("prijmeni"));
                    }else session.setAttribute("eprij", eprij);
                    System.err.println("mail: " + request.getParameter("mail"));
                    if(validateEmail(request.getParameter("mail"))){
                        u.setEmail(request.getParameter("mail"));
                    }else session.setAttribute("eemail", eemail);
                    System.err.println("telefon:" + request.getParameter("telefon"));
                    if(validateTelefon(request.getParameter("telefon"))){
                        u.setTelefon(Integer.valueOf(request.getParameter("telefon")));
                    }else session.setAttribute("etel", etel);
                    System.err.println("heslo: " + request.getParameter("heslo"));
                    System.err.println("heslo2: " + request.getParameter("heslo2"));
                    if(validateHeslo(request.getParameter("heslo"),request.getParameter("heslo2"))){
                        u.setHeslo(SHA1hash.getSHA1(request.getParameter("heslo")));
                        u.setOtevreneHeslo(request.getParameter("heslo"));
                        session.setAttribute("oheslo", oheslo);
                    }else session.setAttribute("eheslo", eheslo);
                    System.err.println("ulice: " + request.getParameter("ulice"));
                    if(validateSlovo(request.getParameter("ulice"))){
                        u.getAdresa().setUlice(request.getParameter("ulice"));
                    }else session.setAttribute("eulice", eulice);
                    System.err.println("cp: " + request.getParameter("cp"));
                    if(validateCp(request.getParameter("cp"))){
                        u.getAdresa().setCp(Integer.valueOf(request.getParameter("cp")));
                    }else session.setAttribute("ecp", ecp);
                    System.err.println("mesto: " + request.getParameter("mesto"));
                    if(validateSlovo(request.getParameter("mesto"))){
                        u.getAdresa().setMesto(request.getParameter("mesto"));
                    }else session.setAttribute("emesto", emesto);
                    System.err.println("psc: " + request.getParameter("psc"));
                    if(validatePsc(request.getParameter("psc"))){
                        u.getAdresa().setPsc(Integer.valueOf(request.getParameter("psc")));
                    }else session.setAttribute("epsc", epsc);
                    u.getAdresa().setStat(request.getParameter("stat"));
                    //pokud je uzivatel pripraven k ulozeni do DB
                    if(UserManager.isAllset(u)){
                        System.err.println("vsechno nastaveno");
                        
//                        u.setIdr(1);
//                        u.getAdresa().setIda(2);
//                        u.setIdu(5);
//                        u.setIda(1);
//                        u.setRole(new Urole(1, "zákazník"));
                        u.setRole(new Urole(1, "zákazník"));
                        //ulozim do db
                        UserManager.vlozData(u);
                        //smazu info ze session
                        //uklidim po sobe
                        clear(session);
                        request.setAttribute("showPage", "registraceOK");
                    }
                }
            }
            RequestDispatcher rd = getServletContext().getRequestDispatcher(viewUrl);
            rd.forward(request, response);
        } finally { 
            //out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private boolean validateSlovo(String slovo) {
        if(slovo.matches("[a-zA-Z\\s]{1,20}")){
            return true;
        }else return false;
    }

    private boolean validateEmail(String email) {
        if(email.matches("[a-zA-Z0-9.-]{2,}@[a-zA-Z]{3,}\\.[a-zA-Z]{2,3}")){
            return true;
        }else return false;
    }

    private boolean validateHeslo(String parameter, String parameter0) {
        if(parameter.equals(parameter0) && parameter.matches(".{6,}")){
            return true;
        }else return false;
    }

    private boolean validateCp(String parameter) {
        if(parameter.matches("^[1-9]{1,1}[0-9]{0,10}")){
            return true;
        }else return false;
    }

    private boolean validatePsc(String parameter) {
        if(parameter.matches("\\d{5,5}")){
            return true;
        }else return false;
    }

    private void smazErr(HttpSession session) {
        session.removeAttribute("ejmeno");
        session.removeAttribute("eprij");
        session.removeAttribute("eemail");
        session.removeAttribute("eheslo");
        session.removeAttribute("oheslo");
        session.removeAttribute("eulice");
        session.removeAttribute("emesto");
        session.removeAttribute("epsc");
        session.removeAttribute("ecp");
    }

    private boolean validateTelefon(String parameter) {
        if(parameter.matches("[1-9]{1,1}[0-9]{8,8}")){
            return true;
        }else return false;
    }

    private void clear(HttpSession session) {
        session.removeAttribute("novyUzivatel");
        session.removeAttribute("ejmeno");
        session.removeAttribute("eprij");
        session.removeAttribute("etel");
        session.removeAttribute("eheslo");
        session.removeAttribute("oheslo");
        session.removeAttribute("emesto");
        session.removeAttribute("eemail");
        session.removeAttribute("eulice");
        session.removeAttribute("epsc");
        session.removeAttribute("ecp");
    }

}
